package cn.bud.msgbus.server.server.subscribe;

import cn.bud.msgbus.server.bean.MsgBody;
import cn.bud.msgbus.server.bean.Subscriber;
import cn.hutool.json.JSONObject;
import cn.hutool.json.JSONUtil;
import lombok.Data;
import lombok.extern.slf4j.Slf4j;

import java.lang.reflect.InvocationTargetException;
import java.lang.reflect.Method;
import java.lang.reflect.Parameter;
import java.util.LinkedHashMap;

/**
 * Subscribtion
 *
 * @author hxj
 * @version 1.0
 * @description
 * @date 2024-06-19 14:14
 */
@Slf4j
@Data
public class LocalSubscriber extends Subscriber {

    private Method method;
    private Object handler;
    private Class<?> dataClazz;

    @Override
    public String name() {
        return handler.getClass().getName()+"#"+ method.getName();
    }

    @Override
    public void sendMsg(MsgBody msg) throws InvocationTargetException, IllegalAccessException {
        if (isTimeUnEffect(msg.getTopic())) {
            return;
        }
        if (method == null || handler == null) {
            return;
        }
        Class<?> clazz = null;
        for (Parameter parameter : method.getParameters()) {
            clazz = parameter.getType();
            if (clazz.isAssignableFrom(msg.getData().getClass()) || msg.getData().getClass().equals(clazz)) {
                method.invoke(handler, msg.getData());
                return;
            }
        }
        if (msg.getData() instanceof LinkedHashMap) {
            LinkedHashMap data = (LinkedHashMap) msg.getData();
            Object obj = null;
            try {
                obj = new JSONObject(data).toBean(clazz);
            }catch (Exception e) {
            }
            if (obj != null) {
                method.invoke(handler, obj);
                return;
            }
        }
        if (msg.getData() instanceof String) {
            Object obj = null;
            try {
                 JSONUtil.toBean(msg.getData().toString(), clazz);
            }catch (Exception e) {
            }
            if (obj != null) {
                method.invoke(handler, obj);
            }else {
                method.invoke(handler, msg.getData());
            }
        }
//        if (dataClazz.equals(Void.class)) {
//            method.invoke(handler, msg.getData());
//        }else if (msg.getData().getClass().equals(dataClazz)) {
//            method.invoke(handler, msg.getData());
//        }else {
//            log.info("本地订阅数据推送：不需要推送的数据，原因：主题匹配，数据class不匹配，" +
//                    "topic={}, targetClazz={}, actClazz={}",
//                    msg.getTopic(), dataClazz, msg.getData().getClass());
//        }

    }
}
